package com.zhiqingchun.web.user;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhiqingchun.dao.article.IArticleDao;
import com.zhiqingchun.dao.category.CategoryResult;
import com.zhiqingchun.dao.category.ICategoryDao;
import com.zhiqingchun.dao.category.impl.CategoryDao;
import com.zhiqingchun.pojo.ArticleDO;
import com.zhiqingchun.pojo.CategoryDO;

@Controller
@RequestMapping("/modifyArticle.html")
public class ModifyArticleController {

	@RequestMapping(method = RequestMethod.GET)
	public String get(ModelMap map, HttpServletRequest request, HttpServletResponse response,
			int id) {
		 ArticleDO articleDO = articleDao.byId(id);
		 map.addAttribute("article", articleDO);
		 
		 // 求出所有一级分类和所属二级分类列表
		 CategoryDO categoryDO = new CategoryDO();
		 categoryDO.setId(0);
		 CategoryResult categoryResult1 = categoryDao.list(categoryDO, null);
		 if (categoryResult1.isSuccess()) {
			map.addAttribute("list1", categoryResult1.getCategoryList());
		 }
		 categoryDO.setId(articleDO.getParentCategory());
		 CategoryResult categoryResult2 = categoryDao.list(categoryDO, null);
		 if (categoryResult2.isSuccess()) {
			map.addAttribute("list2", categoryResult2.getCategoryList());
		 }
		 
		 return "user/modifyArticle";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String get(ModelMap map, HttpServletRequest request, HttpServletResponse response
			) {
		try {
			request.setCharacterEncoding("utf-8") ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		ArticleDO articleDO = new ArticleDO();
		articleDO.setCategory(Integer.parseInt(request.getParameter("category")));
		articleDO.setId(Integer.parseInt(request.getParameter("id")));
		articleDO.setTitle(request.getParameter("title"));
		articleDO.setContent(request.getParameter("content"));
		articleDao.modify(articleDO);
		return "redirect:article.html?id=" + articleDO.getId();
	}
	
	@Autowired
	private IArticleDao articleDao;
	
	@Autowired
	private ICategoryDao categoryDao;

	public ICategoryDao getCategoryDao() {
		return categoryDao;
	}

	public void setCategoryDao(ICategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	public IArticleDao getArticleDao() {
		return articleDao;
	}

	public void setArticleDao(IArticleDao articleDao) {
		this.articleDao = articleDao;
	}
	
}
